package com.wrt.sps.mgt.controller;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import com.wrt.sps.entity.Results;
import com.wrt.sps.mgt.entity.User;
import com.wrt.sps.mgt.pojo.UserDTO;
import com.wrt.sps.mgt.service.UserService;
import com.wrt.sps.utils.MD5Util;

/**
 * 登录接口
 * 
 * @author 文瑞涛
 * @date 2021年1月7日 下午10:21:00
 */
@RestController
public class LoginController {
	
	@Resource
	private UserService userService;

	/**
	 * 
	 * 用户登录
	 * 
	 * @param 含有用户名和密码的登录信息 user
	 * 
	 * @return 登录结果
	 */
	@PostMapping("/mgt/login")
	public Results login(UserDTO user) {
		if (StringUtils.isEmpty(user.getLoginName()) || StringUtils.isEmpty(user.getPassword())) {
			return Results.fail("请输入用户名和密码！", null);
		}
		// 用户认证信息
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(user.getLoginName(),
				MD5Util.encrypt(user.getPassword(), User.SALT));
		try {
			// 进行验证，这里可以捕获异常，然后返回对应信息
			subject.login(usernamePasswordToken);
		} catch (UnknownAccountException e) {
			return Results.fail("用户名不存在！", e.getMessage());
		} catch (AuthenticationException e) {
			if (e.getMessage().equals(Boolean.FALSE.toString())) {
				return Results.fail("账户已禁用！", e.getMessage());
			}
			return Results.fail("账号或密码错误！", e.getMessage());
		} catch (AuthorizationException e) {
			return Results.fail("没有权限！", e.getMessage());
		} finally {
			User loginUser = (User) subject.getPrincipal();
			if(null != loginUser) {
				loginUser.setLastLoginIP(subject.getSession().getHost());
				loginUser.setLastLoginDate(subject.getSession().getLastAccessTime());
				userService.save(loginUser);
			}
		}
		return Results.success("登录成功", null);
	}
}
